package com.exercises;

import java.util.*;

class Exercise1190 {
    public static void main(String[] args) {
        System.out.println(reverseParentheses("(ed(et(oc))el)"));
    }

    public static String reverseParentheses(String s) {
        char[] chars = s.toCharArray();
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.push(i);
            } else if (s.charAt(i) == ')') {
                int a = stack.pop() + 1;
                int b = i - 1;
                while (a < b) {
                    char tmp = chars[a];
                    chars[a] = chars[b];
                    chars[b] = tmp;
                    a++;
                    b--;
                }
            }
        }
        return new String(chars).replaceAll("\\(", "").replace(")", "");
    }
}
